// 加载环境变量
import "dotenv/config.js";
// 导入 express 模块
import express from "express";
// 实例化 Application 对象
const app = express();
// 使用异步错误捕获补丁
import "express-async-errors";
import { MulterError } from "multer";
// 确保 public/avatars 目录存在
import { shouldExistsDir } from "./utils.js";
shouldExistsDir("./public/avatars");
shouldExistsDir("./public/cover");
shouldExistsDir("./public/photo");
// 静态文件服务
app.use(express.static("public"));

// 解析 body 数据
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
// 使用 session 中间件
import session from "express-session";

// 设置信任代理
app.set("trust proxy", 1);
const sessionOptions = {
  secret: process.env.secret,
  resave: true,
  saveUninitialized: true,
  cookie: {
    secure: false,
    httpOnly: false,
    maxAge: 24 * 60 * 60 * 1000,
  },
};

if (process.env.NODE_ENV === "production") {
  // 如果是生产环境，使用 redis 保存 session
  const module = await import("./redis.js");
  sessionOptions.store = module.redisStore;
}
app.use(session(sessionOptions));

// 注册路由
import registerCommonRoutes from "./routers/common.js";
registerCommonRoutes(app);
import registerRoutes from "./routers/authorization.js";
registerRoutes(app);

// 全局错误处理函数
app.use((err, req, res, next) => {
  if (err instanceof MulterError) {
    return res.send({
      success: false,
      errors: {
        [err.field]: [err.code == "LIMIT_FILE_SIZE" ? "文件过大" : err.message],
      },
    });
  }
  console.log(err);
  res.status(500).send({
    success: false,
    message: err.message,
  });
});
// 运行服务
const { PORT } = process.env;
app.listen(Number(PORT), () => {
  console.log(`Server running at http://127.0.0.1:${PORT}`);
});
